package com.my.ph.media.inter.impl;

import cn.hutool.json.JSONObject;
import com.my.ph.enums.MediaTypeEnum;
import com.my.ph.media.api.TMDBApi;
import com.my.ph.entity.media.TVMovie;
import com.my.ph.entity.media.TVMovieDetail;
import com.my.ph.entity.media.TvMovieCredits;
import com.my.ph.media.inter.TvMovieInter;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;

@Component("tmdb")
@RequiredArgsConstructor
public class TMDBTvMovieInterImpl implements TvMovieInter {

    private final TMDBApi tmdbApi;

    @Override
    public List<TVMovie> search(String keyword) {
        return tmdbApi.searchMoveTv(keyword);
    }

    @Override
    public TVMovieDetail getDetail(long id, MediaTypeEnum mediaType) {
        TVMovieDetail detail = tmdbApi.getDetail(id, mediaType);
        JSONObject creditsObj = tmdbApi.getCredits(id, mediaType);
        List<TvMovieCredits> castCredits = creditsObj.getJSONArray("cast").toList(TvMovieCredits.class);
        List<TvMovieCredits> crewCredits = creditsObj.getJSONArray("crew").toList(TvMovieCredits.class);
        detail.setDirectingCredits(crewCredits.stream().filter(item -> "Director".equals(item.getJob())).map(item -> new TVMovieDetail.Credits(item.getName(), item.getOriginalName())).toList());
        detail.setWritingCredits(crewCredits.stream().filter(item -> "Writer".equals(item.getJob())).map(item -> new TVMovieDetail.Credits(item.getName(), item.getOriginalName())).toList());
        detail.setActingCredits(castCredits.stream().map(item -> new TVMovieDetail.Credits(item.getName(), item.getOriginalName())).toList());
        return detail;
    }

}
